package com.ruoyi.quartz.controller;

import cn.hutool.http.HttpUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.domain.WechatyConfig;
import com.ruoyi.quartz.domain.WechatyInfo;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.service.IWechatyConfigService;
import com.ruoyi.quartz.service.IWechatyInfoService;
import com.ruoyi.quartz.vo.WechatyConfigVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 微信机器人配置Controller
 *
 * @author fz
 * @date 2024-04-10
 */
@Slf4j
@RestController
@RequestMapping("/snowRemoving/config")
public class WechatyConfigController extends BaseController {
    @Autowired
    private IWechatyConfigService wechatyConfigService;
    @Autowired
    private IWechatyInfoService wechatyInfoService;
    @Autowired
    private ISysJobService sysJobService;

    /**
     * 查询微信机器人配置列表
     */
    @PreAuthorize("@ss.hasPermi('snowRemoving:config:list')")
    @GetMapping("/list")
    public TableDataInfo list(WechatyConfig wechatyConfig) {
        startPage();
        List<WechatyConfig> list = wechatyConfigService.selectWechatyConfigList(wechatyConfig);
        List<WechatyConfigVo> resultList = new ArrayList<>();
        for (WechatyConfig config : list) {
            WechatyConfigVo vo = new WechatyConfigVo();
            BeanUtils.copyProperties(config, vo);
            if (null != config.getJobId()) {
                SysJob sysJob = sysJobService.selectJobById(config.getJobId());
                vo.setSysJob(sysJob);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出微信机器人配置列表
     */
    @PreAuthorize("@ss.hasPermi('snowRemoving:config:export')")
    @Log(title = "微信机器人配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WechatyConfig wechatyConfig) {
        List<WechatyConfig> list = wechatyConfigService.selectWechatyConfigList(wechatyConfig);
        ExcelUtil<WechatyConfig> util = new ExcelUtil<WechatyConfig>(WechatyConfig.class);
        util.exportExcel(response, list, "微信机器人配置数据");
    }

    /**
     * 获取微信机器人配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('snowRemoving:config:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        WechatyConfig wechatyConfig = wechatyConfigService.selectWechatyConfigById(id);
        WechatyConfigVo vo = new WechatyConfigVo();
        BeanUtils.copyProperties(wechatyConfig, vo);
        if (null != wechatyConfig.getJobId()) {
            SysJob sysJob = sysJobService.selectJobById(wechatyConfig.getJobId());
            vo.setSysJob(sysJob);
        }
        return success(vo);
    }

    /**
     * 新增微信机器人配置
     */
    @PreAuthorize("@ss.hasPermi('snowRemoving:config:add')")
    @Log(title = "微信机器人配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WechatyConfig wechatyConfig) {
        try {
            SysJob sysJob = new SysJob();
            sysJob.setJobName("给群" + wechatyConfig.getRoom() + "发送消息");
            sysJob.setJobGroup("DEFAULT");
            sysJob.setInvokeTarget("wechatyBotTask.sendToRoom('" + wechatyConfig.getRoom() + "','" + wechatyConfig.getPicPath() + "')");
            sysJob.setCronExpression("0/10 * * * * ?");
            sysJob.setMisfirePolicy("2");
            sysJob.setConcurrent("1");
            sysJob.setStatus("0");
            sysJobService.insertJob(sysJob);
            wechatyConfig.setJobId(sysJob.getJobId());
            wechatyConfigService.insertWechatyConfig(wechatyConfig);
            sysJobService.resumeJob(sysJob);
            return success();
        } catch (Exception e) {
            return error("新增失败");
        }
    }

    /**
     * 修改微信机器人配置
     */
    @PreAuthorize("@ss.hasPermi('snowRemoving:config:edit')")
    @Log(title = "微信机器人配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WechatyConfig wechatyConfig) {
        return toAjax(wechatyConfigService.updateWechatyConfig(wechatyConfig));
    }

    /**
     * 删除微信机器人配置
     */
    @PreAuthorize("@ss.hasPermi('snowRemoving:config:remove')")
    @Log(title = "微信机器人配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (Long id : ids) {
            WechatyConfig wechatyConfig = wechatyConfigService.selectWechatyConfigById(id);
            if (null != wechatyConfig.getJobId()) {
                SysJob sysJob = sysJobService.selectJobById(wechatyConfig.getJobId());
                try {
                    sysJobService.deleteJob(sysJob);
                } catch (Exception e) {
                    return error("删除失败");
                }
            }
            wechatyConfigService.deleteWechatyConfigById(id);
        }
        return success();
    }

    @PostMapping("/qrcode")
    public AjaxResult qrcode(@RequestBody Map<String, Object> map) {
        log.info("qrcodeUrl:{}", map.get("qrcodeUrl"));
        WechatyInfo wechatyInfo= wechatyInfoService.selectWechatyInfoById(1);
        wechatyInfo.setQrcodeUrl(map.get("qrcodeUrl").toString());
        wechatyInfoService.updateWechatyInfo(wechatyInfo);
        return success();
    }

    @GetMapping("/test")
    public AjaxResult test() {
        String result = HttpUtil.get("http://localhost:13000/getStatus", 5000);
        log.info("微信机器人心跳检测结果:{}", result);

        return success();
    }
}
